package NetWork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private  int serverPort;
    public UdpEchoClient(String ip, int port) throws SocketException {
        socket = new DatagramSocket();
        serverIp = ip;
        serverPort = port;
    }
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true){
            //1、先从控制台读取用户输入的字符串
            System.out.print("->");
            String request = scanner.next();
            //2、把这个用户输入的内容，构造成一个UDP请求，并发送
            //构造的请求包含两部分信息
            //1）数据的内容，request字符串
            //2) 数据要发给谁 服务器的IP+端口
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            //3、从服务器读取响应数据并解析
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength(),"UTF-8");
            //4、把响应结果显示到控制台上。
            System.out.printf("req: %s, resp: %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        //由于客户端和服务器在同一个机器上 使用的IP仍然是127.0.0.1
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();

    }
}
